package net.dgg.dggcloud.service.jrcrm.service.customer.api;

import net.dgg.dggcloud.core.util.CalendarUtils;
import net.dgg.dggcloud.core.util.DateUtil;
import net.dgg.dggcloud.core.util.StringUtils;
import net.dgg.dggcloud.service.common.base.SessionManager;
import net.dgg.dggcloud.service.common.base.service.BaseService;
import net.dgg.dggcloud.service.common.exception.BizException;
import net.dgg.dggcloud.service.jrcrm.constant.CustomerAttrConstant;
import net.dgg.dggcloud.service.jrcrm.constant.CustomerConstant;
import net.dgg.dggcloud.service.jrcrm.dao.customer.CustomerDao;
import net.dgg.dggcloud.service.jrcrm.entity.business.Business;
import net.dgg.dggcloud.service.jrcrm.entity.cms.TreeBook;
import net.dgg.dggcloud.service.jrcrm.entity.customer.*;
import net.dgg.dggcloud.service.entity.user.User;
import net.dgg.dggcloud.service.jrcrm.service.business.BusinessAbilityService;
import net.dgg.dggcloud.service.jrcrm.service.business.BusinessService;
import net.dgg.dggcloud.service.jrcrm.service.cms.TreeBookService;
import net.dgg.dggcloud.service.jrcrm.service.customer.CustomerService;
import net.dgg.dggcloud.service.jrcrm.utils.TranslateMapUtil;
import net.dgg.dggcloud.service.jrcrm.vo.CusAttrVo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;


/**
 * 客户属性业务处理接口
 * @ClassName: CustomerAttrApiService
 * @Author: 周潮
 * @Date: 2017年11月10 11:36:08
 * @Version V1.0
 */

@Service
public class CustomerAttrApiService extends BaseService{

    @Autowired
    private CustomerDao customerDao;
    @Resource
    private CustomerService customerService;

    @Autowired
    private TreeBookService treeBookService;

    @Resource
    private BusinessAbilityService businessAbilityService;

    @Resource
    private BusinessService businessService;
    /**
     * 新增客户资质
     * @param map
     * @return
     */
    public CusAttrVo saveAttr(Map map){
        if(null == map.get("customerId")){
            throw new BizException("新增客户属性失败！客户id为空！", 10005);
        }else if(null == map.get("customerAttr")){
            throw new BizException("新增客户属性失败！客户属性获取失败！", 10005);
        }else if(null == map.get("User")){
            throw new BizException("新增客户属性失败！新增人信息为空！", 10005);
        }else if(null == map.get("customer")){
            throw new BizException("新增客户属性失败！未找到该客户！", 10005);
        }
        Long customerId = Long.valueOf(map.get("customerId").toString());
        //查询客户是否存在
        Customer customer = (Customer) map.get("customer");
        if(null == customer){
            throw new BizException("新增客户属性失败！客户不存在！", 10005);
        }
        User user = (User) map.get("User");
        //获取客户属性Vo
        CusAttrVo cusAttrVo = (CusAttrVo) map.get("customerAttr");
        String customerAttrFlag = "";
        if(null != cusAttrVo.getAttrBuildings()){
            customerAttrFlag += CustomerAttrConstant.CUS_ATTR_OWN_HOUSE + ",";//有房
        }
        if(null != cusAttrVo.getAttrVehicles()){
            customerAttrFlag += CustomerAttrConstant.CUS_ATTR_OWN_CAR + ",";//有车
        }
        if(null != cusAttrVo.getAttrPolicy()){
            customerAttrFlag += CustomerAttrConstant.CUS_ATTR_OWN_POLICY + ",";//有保单
        }
        if(null != cusAttrVo.getAttrJob()){
            customerAttrFlag += CustomerAttrConstant.CUS_ATTR_OWN_JOB + ",";//有工作
        }
        if(null != cusAttrVo.getAttrSocialSecurity()){
            customerAttrFlag += CustomerAttrConstant.CUS_ATTR_OWN_SB + ",";//有社保
        }
        if(null != cusAttrVo.getAttrAccFund()){
            customerAttrFlag += CustomerAttrConstant.CUS_ATTR_OWN_GJJ + ",";//有公积金
        }
        if(null != cusAttrVo.getAttrCreditCard()){
            customerAttrFlag += CustomerAttrConstant.CUS_ATTR_OWN_XYK + ",";//有信用卡
        }
        if(null != cusAttrVo.getAttrOther()&&null!= cusAttrVo.getAttrOther().getAmount()){
            customerAttrFlag += CustomerAttrConstant.CUS_ATTR_OTHER__TYPE + ",";//其他
        }
        if(null != cusAttrVo.getAttrNo() && StringUtils.isNotBlank(cusAttrVo.getAttrNo().getRemark())){
            if(StringUtils.isNotBlank(cusAttrVo.getAttrNo().getRemark().trim())) {
                customerAttrFlag += CustomerAttrConstant.CUS_ATTR_NO + ",";//无资质
            }
        }
        if(StringUtils.isNotEmpty(customerAttrFlag)){//保存客户属性值到客户表中
            customer.setCustomerAttrFlag(customerAttrFlag.substring(0, customerAttrFlag.length() - 1));
        }

        //保存客户属性到客户表
        customerService.saveCustomerRecord(customer.getId(), customer.getNo(), Customer.TABLE_NAME, customer.getId(), CustomerConstant.CUS_OPERATE_ATTR_UPDATE, user.getId(), "更新客户属性");

        //保存房产
        if(null != cusAttrVo.getAttrBuildings() && cusAttrVo.getAttrBuildings().size() > 0){
            for (AttrBuilding building: cusAttrVo.getAttrBuildings()) {
                building.setCustomerId(customerId);
                building.setCreateUser(user);
                if(null == building.getId()){
                    long id = this.keyWorker.nextId();
                    building.setId(id);
                    repository.save(building);
                }else{
                    repository.saveOrUpdate(building);
                }

//                customerService.saveCustomerRecord(customer.getId(), customer.getNo(), AttrBuilding.TABLE_NAME, building.getId(), CustomerConstant.CUS_OPERATE_ATTR_UPDATE, user.getId(), "更新客户属性-房产");
            }
        }

        //保存车辆
        if(null != cusAttrVo.getAttrVehicles() && cusAttrVo.getAttrVehicles().size() > 0) {
            for (AttrVehicle vehicle : cusAttrVo.getAttrVehicles()) {
                vehicle.setCustomerId(customerId);
                vehicle.setCreateUser(user);
                if(null == vehicle.getId()){
                    long id = this.keyWorker.nextId();
                    vehicle.setId(id);
                    repository.save(vehicle);
                }else {
                    repository.saveOrUpdate(vehicle);
                }

//                customerService.saveCustomerRecord(customer.getId(), customer.getNo(), AttrVehicle.TABLE_NAME, vehicle.getId(), CustomerConstant.CUS_OPERATE_ATTR_UPDATE, user.getId(), "更新客户属性-车辆");
            }
        }

        //保存保单
        if(null != cusAttrVo.getAttrPolicy()) {
            AttrPolicy attrPolicy = cusAttrVo.getAttrPolicy();
            attrPolicy.setCustomerId(customerId);
            attrPolicy.setCreateUser(user);
            if(null == attrPolicy.getId()){
                long id = this.keyWorker.nextId();
                attrPolicy.setId(id);
                repository.save(attrPolicy);
            }else {
                repository.saveOrUpdate(attrPolicy);
            }

//            customerService.saveCustomerRecord(customer.getId(), customer.getNo(), AttrPolicy.TABLE_NAME, attrPolicy.getId(), CustomerConstant.CUS_OPERATE_ATTR_UPDATE, user.getId(), "更新客户属性-保单");
        }

        //保存工作
        if(null != cusAttrVo.getAttrJob()) {
            AttrJob attrJob = cusAttrVo.getAttrJob();
            attrJob.setCustomerId(customerId);
            attrJob.setCreateUser(user);
            if(null == attrJob.getId()){
                long id = this.keyWorker.nextId();
                attrJob.setId(id);
                repository.save(attrJob);
            }else {
                repository.saveOrUpdate(attrJob);
            }

//            customerService.saveCustomerRecord(customer.getId(), customer.getNo(), AttrJob.TABLE_NAME, attrJob.getId(), CustomerConstant.CUS_OPERATE_ATTR_UPDATE, user.getId(), "更新客户属性-工作");
        }

        //保存社保
        if(null != cusAttrVo.getAttrSocialSecurity()) {
            AttrSocialSecurity attrSocialSecurity = cusAttrVo.getAttrSocialSecurity();
            attrSocialSecurity.setCustomerId(customerId);
            attrSocialSecurity.setCreateUser(user);
            if(null == attrSocialSecurity.getId()){
                long id = this.keyWorker.nextId();
                attrSocialSecurity.setId(id);
                repository.save(attrSocialSecurity);
            }else {
                repository.saveOrUpdate(attrSocialSecurity);
            }

//            customerService.saveCustomerRecord(customer.getId(), customer.getNo(), AttrSocialSecurity.TABLE_NAME, attrSocialSecurity.getId(), CustomerConstant.CUS_OPERATE_ATTR_UPDATE, user.getId(), "更新客户属性-社保");
        }

        //保存公积金
        if(null != cusAttrVo.getAttrAccFund()) {
            AttrAccFund attrAccFund = cusAttrVo.getAttrAccFund();
            attrAccFund.setCustomerId(customerId);
            attrAccFund.setCreateUser(user);
            if(null == attrAccFund.getId()){
                long id = this.keyWorker.nextId();
                attrAccFund.setId(id);
                repository.save(attrAccFund);
            }else {
                repository.saveOrUpdate(attrAccFund);
            }

//            customerService.saveCustomerRecord(customer.getId(), customer.getNo(), AttrAccFund.TABLE_NAME, attrAccFund.getId(), CustomerConstant.CUS_OPERATE_ATTR_UPDATE, user.getId(), "更新客户属性-公积金");
        }

        //保存负债
        if(null != cusAttrVo.getAttrLiability()) {
            AttrLiability attrLiability = cusAttrVo.getAttrLiability();
            attrLiability.setCustomerId(customerId);
            attrLiability.setCreateUser(user);
            if(null == attrLiability.getId()){
                long id = this.keyWorker.nextId();
                attrLiability.setId(id);
                repository.save(attrLiability);
            }else {
                repository.saveOrUpdate(attrLiability);
            }

//            customerService.saveCustomerRecord(customer.getId(), customer.getNo(), AttrLiability.TABLE_NAME, attrLiability.getId(), CustomerConstant.CUS_OPERATE_ATTR_UPDATE, user.getId(), "更新客户属性-负债");
        }

        //保存信用卡
        if(null != cusAttrVo.getAttrCreditCard()) {
            AttrCreditCard attrCreditCard = cusAttrVo.getAttrCreditCard();
            attrCreditCard.setCustomerId(customerId);
            attrCreditCard.setCreateUser(user);
            if(null == attrCreditCard.getId()){
                long id = this.keyWorker.nextId();
                attrCreditCard.setId(id);
                repository.save(attrCreditCard);
            }else {
                repository.saveOrUpdate(attrCreditCard);
            }

//            customerService.saveCustomerRecord(customer.getId(), customer.getNo(), AttrCreditCard.TABLE_NAME, attrCreditCard.getId(), CustomerConstant.CUS_OPERATE_ATTR_UPDATE, user.getId(), "更新客户属性-信用卡");
        }

        //保存其他
        if(null != cusAttrVo.getAttrOther()&&null!= cusAttrVo.getAttrOther().getAmount()) {
            AttrOther attrOther = cusAttrVo.getAttrOther();
            attrOther.setCustomerId(customerId);
            attrOther.setCreateUser(user);
            if(null == attrOther.getId()){
                long id = this.keyWorker.nextId();
                attrOther.setId(id);
                repository.save(attrOther);
            }else {
                repository.saveOrUpdate(attrOther);
            }
//            customerService.saveCustomerRecord(customer.getId(), customer.getNo(), AttrCreditCard.TABLE_NAME, attrCreditCard.getId(), CustomerConstant.CUS_OPERATE_ATTR_UPDATE, user.getId(), "更新客户属性-信用卡");
        }

        //保存无资质
        if(null != cusAttrVo.getAttrNo()) {
            AttrNo attrNo = cusAttrVo.getAttrNo();
            if(StringUtils.isNotBlank(attrNo.getRemark())) {
                if(StringUtils.isNotBlank(attrNo.getRemark().trim())) {
                    attrNo.setCustomerId(customerId);
                    attrNo.setUpdaterUser(user);
                    if (null == attrNo.getId()) {
                        long id = this.keyWorker.nextId();
                        attrNo.setId(id);
                        attrNo.setCreateUser(user);
                        repository.save(attrNo);
                    } else {
                        repository.saveOrUpdate(attrNo);
                    }
                }else{
                    if(null != attrNo.getId()){
                        repository.deleteEntityById(AttrNo.class, attrNo.getId());
                    }
                }
            }else{
                if(null != attrNo.getId()){
                    repository.deleteEntityById(AttrNo.class, attrNo.getId());
                }
            }
        }
//        customerAttrFlag,customerId
        //调用商机接口修改商机上的客户属性信息
//        businessAbilityService.updateCustomerBusinessAttr(customerAttrFlag,customerId);
        //只更新客户的最新商机的属性
        if (null != customer.getLastBusId()) {
            Business business = businessAbilityService.getBusinessById(customer.getLastBusId());
            if (null != business) {
                business.setCustomerAttr(customerAttrFlag);
                repository.saveOrUpdate(business);
            }
        }

        return cusAttrVo;
    }



    /**
     * 根据客户id查询客户属性
     *  customerId：客户id
     * @return
     */
    public CusAttrVo findCustomerAttrsByCustomerId(Map map) throws IllegalAccessException {
        if (null == map.get("customerId")) {
            return null;
        }
        Long customerId = Long.parseLong(map.get("customerId").toString());
        CusAttrVo cusAttrVo = new CusAttrVo();
        Query query;
        String[] arrList = {"AttrBuilding", "AttrVehicle", "AttrAccFund", "AttrJob", "AttrLiability", "AttrPolicy", "AttrSocialSecurity", "AttrCreditCard","AttrOther","AttrNo"};
        for (int i = 0; i < arrList.length; i++) {
            query = repository.getSession().createQuery("from " + arrList[i] + " where customerId = ? ");
            query.setParameter(0, customerId);
            switch (i) {
                case 0:
                    cusAttrVo.setAttrBuildings((List<AttrBuilding>) query.list());
                    break;
                case 1:
                    cusAttrVo.setAttrVehicles((List<AttrVehicle>) query.list());
                    break;
                case 2:
                    cusAttrVo.setAttrAccFund((AttrAccFund) query.uniqueResult());
                    break;
                case 3:
                    cusAttrVo.setAttrJob((AttrJob) query.uniqueResult());
                    break;
                case 4:
                    cusAttrVo.setAttrLiability((AttrLiability) query.uniqueResult());
                    break;
                case 5:
                    cusAttrVo.setAttrPolicy((AttrPolicy) query.uniqueResult());
                    break;
                case 6:
                    cusAttrVo.setAttrSocialSecurity((AttrSocialSecurity) query.uniqueResult());
                    break;
                case 7:
                    cusAttrVo.setAttrCreditCard((AttrCreditCard) query.uniqueResult());
                    break;
                case 8:
                    cusAttrVo.setAttrOther((AttrOther) query.uniqueResult());
                    break;
                case 9:
                    cusAttrVo.setAttrNo((AttrNo) query.uniqueResult());
                    break;
            }
        }
            return cusAttrVo;
    }



    /**
     * 根据客户表单信息封装客户属性
     * @return
     */
    public CusAttrVo findCustomerAttrsByCustomerForm(Map map) throws IllegalAccessException {
        if (null == map.get("customerPhone")) {
            return null;
        }
        String customerPhone = map.get("customerPhone").toString();
        Query query = repository.getSession().createQuery("From CustomerForm where phone ='"+customerPhone+"'");
        CustomerForm  cf = null;
        CusAttrVo cusAttrVo = new CusAttrVo();
        if(query.list().size()>0) {
            cf = (CustomerForm) query.list().get(0);
        }else{
            return null;
        }

        if(null!=cf.getIsHouse()&&cf.getIsHouse()==1){  //有按揭房
            AttrBuilding ab = new AttrBuilding();
            List<AttrBuilding> list = new ArrayList();
            ab.setPayType(2);
            ab.setBuildingType("HOUSE_TYPE_1");
            list.add(ab);
            cusAttrVo.setAttrBuildings(list);
        }
        if(null!=cf.getIsHouse()&&cf.getIsHouse()==2){  //有全款房
            AttrBuilding ab = new AttrBuilding();
            List<AttrBuilding> list = new ArrayList();
            ab.setPayType(1);
            ab.setBuildingType("HOUSE_TYPE_1");
            list.add(ab);
            cusAttrVo.setAttrBuildings(list);
        }
        if(null!=cf.getIsCar()&&cf.getIsCar()==1){  //有按揭车
            AttrVehicle av = new AttrVehicle();
            List<AttrVehicle> list = new ArrayList();
            av.setPayType(2);
            list.add(av);
            cusAttrVo.setAttrVehicles(list);
        }
        if(null!=cf.getIsCar()&&cf.getIsCar()==2){  //有全款车
            AttrVehicle av = new AttrVehicle();
            List<AttrVehicle> list = new ArrayList();
            av.setPayType(1);
            list.add(av);
            cusAttrVo.setAttrVehicles(list);
        }

        if(null!=cf.getIsFund()&&cf.getIsFund()==1){  //有公积金
            AttrAccFund aa = new AttrAccFund();
            cusAttrVo.setAttrAccFund(aa);

        }

        if(null!=cf.getIsGuaranteeSlip()&&cf.getIsGuaranteeSlip()==1){  //有保单
            AttrPolicy ap = new AttrPolicy();
            cusAttrVo.setAttrPolicy(ap);
        }
        if(null!=cf.getIsCreditCard()&&cf.getIsCreditCard()==1){  //有信用卡
            AttrCreditCard acc = new AttrCreditCard();
            cusAttrVo.setAttrCreditCard(acc);
        }
        if(null!=cf.getIsSocialSecurity()&&cf.getIsSocialSecurity()==1){  //有社保
            AttrSocialSecurity ass = new AttrSocialSecurity();
            cusAttrVo.setAttrSocialSecurity(ass);
        }
        if(null!=cf.getIsOther()&&cf.getIsOther()==1){  //微粒贷
            AttrOther ao = new AttrOther();
            ao.setOther("CUS_KHZZ_OTHER_WLD");
            ao.setAmount(NumberUtils.toDouble(cf.getOtherValue()+""));
            cusAttrVo.setAttrOther(ao);
        }
        if(null!=cf.getIsOther()&&cf.getIsOther()==2){  //芝麻
            AttrOther ao = new AttrOther();
            ao.setOther("CUS_KHZZ_OTHER_ZMXX");
            ao.setAmount(NumberUtils.toDouble(cf.getOtherValue()+""));
            cusAttrVo.setAttrOther(ao);
        }
        if(null!=cf.getIsBuilding()&&cf.getIsBuilding()==1){  //有商品房按揭
            AttrBuilding ab = new AttrBuilding();
            List<AttrBuilding> list = new ArrayList();
            ab.setPayType(2);
            ab.setBuildingType("HOUSE_TYPE_1");
            list.add(ab);
            cusAttrVo.setAttrBuildings(list);
        }
        if(null!=cf.getIsBuilding()&&cf.getIsBuilding()==2){  //有商品全款房
            AttrBuilding ab = new AttrBuilding();
            List<AttrBuilding> list = new ArrayList();
            ab.setPayType(1);
            ab.setBuildingType("HOUSE_TYPE_1");
            list.add(ab);
            cusAttrVo.setAttrBuildings(list);
        }
        if(null!=cf.getIsShop()&&cf.getIsShop()==1){  //有商铺按揭
            AttrBuilding ab = new AttrBuilding();
            List<AttrBuilding> list = new ArrayList();
            ab.setPayType(2);
            ab.setBuildingType("HOUSE_TYPE_2");
            list.add(ab);
            cusAttrVo.setAttrBuildings(list);
        }
        if(null!=cf.getIsShop()&&cf.getIsShop()==2){  //有商铺全款
            AttrBuilding ab = new AttrBuilding();
            List<AttrBuilding> list = new ArrayList();
            ab.setPayType(1);
            ab.setBuildingType("HOUSE_TYPE_2");
            list.add(ab);
            cusAttrVo.setAttrBuildings(list);
        }
        if(null!=cf.getIsOffice()&&cf.getIsOffice()==1){  //有写字楼按揭
            AttrBuilding ab = new AttrBuilding();
            List<AttrBuilding> list = new ArrayList();
            ab.setPayType(2);
            ab.setBuildingType("HOUSE_TYPE_4");
            list.add(ab);
            cusAttrVo.setAttrBuildings(list);
        }
        if(null!=cf.getIsShop()&&cf.getIsShop()==2){  //有
            AttrBuilding ab = new AttrBuilding();
            List<AttrBuilding> list = new ArrayList();
            ab.setPayType(1);
            ab.setBuildingType("HOUSE_TYPE_4");
            list.add(ab);
            cusAttrVo.setAttrBuildings(list);
        }

        return cusAttrVo;
    }



    /**
     * 根据客户表单信息封装客户属性
     * @return
     */
    public CusAttrVo findCustomerAttrsByCustomerOrgin(Map map) throws IllegalAccessException {
        CusAttrVo cusAttrVo = new CusAttrVo();
//        if(map.get("fwdk").equals("是")){  //有按揭房
////            AttrBuilding ab = new AttrBuilding();
////            List<AttrBuilding> list = new ArrayList();
////            ab.setPayType(2);
////            ab.setBuildingType("HOUSE_TYPE_1");
////            list.add(ab);
////            cusAttrVo.setAttrBuildings(list);
////        }
        if(null!=map.get("fwdk")&&map.get("fwdk").equals("有")){  //有全款房
            AttrBuilding ab = new AttrBuilding();
            List<AttrBuilding> list = new ArrayList();
            ab.setPayType(1);
            ab.setBuildingType("HOUSE_TYPE_1");
            list.add(ab);
            cusAttrVo.setAttrBuildings(list);
        }
//        if(map.get("bddk").equals("是")){  //有按揭车
//            AttrVehicle av = new AttrVehicle();
//            List<AttrVehicle> list = new ArrayList();
//            av.setPayType(2);
//            list.add(av);
//            cusAttrVo.setAttrVehicles(list);
//        }
        if(null!=map.get("cldk")&&map.get("cldk").equals("有")){  //有全款车
            AttrVehicle av = new AttrVehicle();
            List<AttrVehicle> list = new ArrayList();
            av.setPayType(1);
            list.add(av);
            cusAttrVo.setAttrVehicles(list);
        }
        if(null!=map.get("gjdk")&&map.get("gjdk").equals("有")){  //有公积金
            AttrAccFund aa = new AttrAccFund();
            cusAttrVo.setAttrAccFund(aa);

        }

        if(null!=map.get("bddk")&&map.get("bddk").equals("有")){  //有保单
            AttrPolicy ap = new AttrPolicy();
            cusAttrVo.setAttrPolicy(ap);
        }
        if(null!=map.get("sbdk")&&map.get("sbdk").equals("有")){  //有社保
            AttrSocialSecurity ass = new AttrSocialSecurity();
            cusAttrVo.setAttrSocialSecurity(ass);
        }
        return cusAttrVo;
    }


    /**
     * 根据客户id修改客户星级
     * @param customer 客户
     * @param business 商机
     * @param cusAttrVo 客户属性
     */
    public void updateCustomerLevel(Customer customer, Business business, CusAttrVo cusAttrVo, User operator){
        if(null == customer){
            return;
        }
        // 初始化总分数为0
        BigDecimal totalBigDecimal = new BigDecimal("0");

        // 商机相关加分
        if(null != business){
            totalBigDecimal = addBusinessScore(business, totalBigDecimal);
        }

        // 客户基本信息加分
        totalBigDecimal = addBaseInfoScore(customer,totalBigDecimal);

        //客户属性评分
        if(null != cusAttrVo){

            if(null != cusAttrVo.getAttrBuildings()){
                // 客户房产信息
                List<AttrBuilding> attrBuildingList =  cusAttrVo.getAttrBuildings();
                if (CollectionUtils.isNotEmpty(attrBuildingList)){
                    for (AttrBuilding attrBuilding : attrBuildingList){
                        // 计算房产分数
                        totalBigDecimal = addBuildingScore(attrBuilding,totalBigDecimal);
                    }
                }
            }

            if(null != cusAttrVo.getAttrVehicles()) {
                // 客户车辆信息
                List<AttrVehicle> attrVehicleList = cusAttrVo.getAttrVehicles();
                if (CollectionUtils.isNotEmpty(attrVehicleList)) {
                    for (AttrVehicle attrVehicle : attrVehicleList) {
                        // 计算车辆分数
                        totalBigDecimal = addVehicleScore(attrVehicle, totalBigDecimal);
                    }
                }
            }

            if(null != cusAttrVo.getAttrPolicy()) {
                // 客户保单信息
                AttrPolicy attrPolicy = cusAttrVo.getAttrPolicy();
                // 计算保单分数
                totalBigDecimal = addPolicyScore(attrPolicy, totalBigDecimal);
            }

            if(null != cusAttrVo.getAttrJob()) {
                // 客户工作信息
                AttrJob attrJob = cusAttrVo.getAttrJob();
                // 计算工作分数
                totalBigDecimal = addJobScore(attrJob, totalBigDecimal);
            }

            if(null != cusAttrVo.getAttrAccFund()) {
                // 客户公积金
                AttrAccFund attrAccFund = cusAttrVo.getAttrAccFund();
                // 计算公积金分数
                totalBigDecimal = addAccFundScore(attrAccFund, totalBigDecimal);
            }

            if(null != cusAttrVo.getAttrSocialSecurity()) {
                // 客户社保信息
                AttrSocialSecurity attrSocialSecurity = cusAttrVo.getAttrSocialSecurity();
                totalBigDecimal = addSocialSecurityScore(attrSocialSecurity, totalBigDecimal);
            }

            if(null != cusAttrVo.getAttrLiability()) {
                // 客户负债信息
                AttrLiability attrLiability = cusAttrVo.getAttrLiability();

                // 计算负债分数
                totalBigDecimal = addLiabilityScore(attrLiability, totalBigDecimal);
            }

            if(null != cusAttrVo.getAttrCreditCard()) {
                // 客户信用卡信息
                AttrCreditCard attrCreditCardList = cusAttrVo.getAttrCreditCard();
            }
        }


        int levelIndex = totalBigDecimal.divide(new BigDecimal(10),0,BigDecimal.ROUND_HALF_UP).intValue();
        String[] levelArr = {null,"CUS_KHZZ_STAR_0.5","CUS_KHZZ_STAR_1","CUS_KHZZ_STAR_1.5","CUS_KHZZ_STAR_2","CUS_KHZZ_STAR_2.5","CUS_KHZZ_STAR_3",
                                "CUS_KHZZ_STAR_3.5","CUS_KHZZ_STAR_4","CUS_KHZZ_STAR_4.5","CUS_KHZZ_STAR_5"};

        levelIndex = levelIndex > 10 ? 10 :levelIndex;
        levelIndex = levelIndex < 0 ? 0 : levelIndex;

        customer.setLevel(levelArr[levelIndex]);
        customer.setUpdaterUser(operator);
        repository.saveOrUpdate(customer);

        // 保存客户操作记录
        //不写修改星级操作记录
     //   customerService.saveCustomerRecord(customer.getId(), customer.getNo(), Customer.TABLE_NAME, customer.getId(), CustomerConstant.CUS_UPDATE_LEVEL, operator.getId(), "更新客户星级");
    }

    /**
     * 计算负债分数
     * @param attrLiability 负债信息
     * @param totalBigDecimal 总分数
     * @return 计算后的总分数
     */
    private BigDecimal addLiabilityScore(AttrLiability attrLiability, BigDecimal totalBigDecimal) {
        if (StringUtils.isNotBlank(attrLiability.getIsOverdue())){
            totalBigDecimal = getTreeBookScore(attrLiability.getIsOverdue(), totalBigDecimal);
        }
        return totalBigDecimal;
    }

    /**
     * 根据最新商机获取商机加分
     * @param business 最新商机
     * @param totalBigDecimal 总分数
     */
    private BigDecimal addBusinessScore(Business business, BigDecimal totalBigDecimal) {
        if (null == business){
            return totalBigDecimal;
        }

        // 新增方式
        if (StringUtils.isNotBlank(business.getAddTypeCode())){
            totalBigDecimal = getTreeBookScore(business.getAddTypeCode(), totalBigDecimal);
        }

        // 贷款金额
        if (null != business.getLoanAmount()){
            // 贷款金额（分）
            BigDecimal loanAmount = new BigDecimal(business.getLoanAmount());
            String amountScore = "0";
            // 万到分的换算单位
            long unit = 1000000L;
            if (loanAmount.compareTo(new BigDecimal(5L*unit)) < 0){
                amountScore = "4";
            } else if (loanAmount.compareTo(new BigDecimal(5L*unit)) >= 0 && loanAmount.compareTo(new BigDecimal(10L*unit)) < 0){
                amountScore = "6";
            } else if (loanAmount.compareTo(new BigDecimal(10L*unit)) >= 0 && loanAmount.compareTo(new BigDecimal(50L*unit)) < 0){
                amountScore = "8";
            } else if (loanAmount.compareTo(new BigDecimal(50L*unit)) >= 0 && loanAmount.compareTo(new BigDecimal(100L*unit)) < 0){
                amountScore = "10";
            } else if (loanAmount.compareTo(new BigDecimal(100L*unit)) >= 0 && loanAmount.compareTo(new BigDecimal(500L*unit)) < 0){
                amountScore = "12";
            } else if (loanAmount.compareTo(new BigDecimal(500L*unit)) >= 0){
                amountScore = "14";
            }
            totalBigDecimal = totalBigDecimal.add(new BigDecimal(amountScore));
        }

        // 用款时间
        if (StringUtils.isNotBlank(business.getLoanTime())){
            totalBigDecimal = getTreeBookScore(business.getLoanTime(), totalBigDecimal);
        }
        // 贷款周期
        if (StringUtils.isNotBlank(business.getLoanCycle())){
            totalBigDecimal = getTreeBookScore(business.getLoanCycle(), totalBigDecimal);
        }
        // 还款方式
        if (StringUtils.isNotBlank(business.getRepaymentType())){
            totalBigDecimal = getTreeBookScore(business.getRepaymentType(), totalBigDecimal);
        }
        // 利息
        if (StringUtils.isNotBlank(business.getLoadInterrestValue())){
            totalBigDecimal = getTreeBookScore(business.getLoadInterrestValue(), totalBigDecimal);
        }
        return totalBigDecimal;
    }

    /**
     * 计算社保分数
     * @param attrSocialSecurity 社保数据
     * @param totalBigDecimal 总分数
     */
    private BigDecimal addSocialSecurityScore(AttrSocialSecurity attrSocialSecurity, BigDecimal totalBigDecimal) {
        // 购买人
        if (StringUtils.isNotBlank(attrSocialSecurity.getPurchaser())){
            totalBigDecimal = getTreeBookScore(attrSocialSecurity.getPurchaser(), totalBigDecimal);
        }
        // 年限
        if (null != attrSocialSecurity.getSocialSecurityYears()){
            // 小于1年
            if (attrSocialSecurity.getSocialSecurityYears() < 1){
                totalBigDecimal = totalBigDecimal.add(new BigDecimal("0.3"));
            } else {
                totalBigDecimal = totalBigDecimal.add(new BigDecimal("0.5"));
            }
        }
        return totalBigDecimal;
    }

    /**
     * 计算公积金分数
     * @param attrAccFund 公积金数据
     * @param totalBigDecimal 总分数
     */
    private BigDecimal addAccFundScore(AttrAccFund attrAccFund, BigDecimal totalBigDecimal) {
        // 公积金基数
        if (null != attrAccFund.getAccFundBase()){
            // 小于4000
            if (attrAccFund.getAccFundBase() < 4000){
                totalBigDecimal = totalBigDecimal.add(new BigDecimal("0.5"));
            } else {
                totalBigDecimal = totalBigDecimal.add(new BigDecimal("1"));
            }
        }
        // 年限
        if (null != attrAccFund.getPaymentYears()){
            // 小于1年
            if (attrAccFund.getPaymentYears() < 1){
                totalBigDecimal = totalBigDecimal.add(new BigDecimal("0.3"));
            } else {
                totalBigDecimal = totalBigDecimal.add(new BigDecimal("0.5"));
            }
        }
        // 购买方式默认满分
        totalBigDecimal = totalBigDecimal.add(new BigDecimal("0.5"));
        return totalBigDecimal;
    }

    /**
     * 计算工作分数
     * @param attrJob 工作
     * @param totalBigDecimal 总分数
     */
    private BigDecimal addJobScore(AttrJob attrJob, BigDecimal totalBigDecimal) {

        /*============================自顾人群==============================*/
        // 开始经营时间
        if (null != attrJob.getStartOperateTime()){
            // 1年以内
            if (new Date().compareTo(CalendarUtils.addYears(attrJob.getStartOperateTime(),1)) == -1){
                totalBigDecimal = totalBigDecimal.add(new BigDecimal("0.5"));
            } else if (new Date().compareTo(CalendarUtils.addYears(attrJob.getStartOperateTime(),3)) == -1){
                totalBigDecimal = totalBigDecimal.add(new BigDecimal("1"));
            } else if (new Date().compareTo(CalendarUtils.addYears(attrJob.getStartOperateTime(),3)) >= 0){
                totalBigDecimal = totalBigDecimal.add(new BigDecimal("2"));
            }
        }
        // 经营流水（万元）
        if (null != attrJob.getOperatingStream()){
            if (attrJob.getOperatingStream() >= 20 && attrJob.getOperatingStream() < 100){
                totalBigDecimal = totalBigDecimal.add(new BigDecimal("1"));
            } else if (attrJob.getOperatingStream() >= 100){
                totalBigDecimal = totalBigDecimal.add(new BigDecimal("2"));
            }
        }
        // 经营行业默认满分
        if (StringUtils.isNotBlank(attrJob.getManagementIndustry())){
            totalBigDecimal = totalBigDecimal.add(new BigDecimal("2"));
        }
        // 经营执照
        if (null != attrJob.getBusinessLicense() && 1 == attrJob.getBusinessLicense()){
            totalBigDecimal = totalBigDecimal.add(new BigDecimal("2"));
        }
        // 占股
        if (null != attrJob.getTotalShares()){
            // 20% 以上
            if (attrJob.getTotalShares().compareTo(20F) >= 0){
                totalBigDecimal = totalBigDecimal.add(new BigDecimal("2"));
            } else {
                totalBigDecimal = totalBigDecimal.add(new BigDecimal("1"));
            }
        }

        /*============================上班人群==============================*/
        // 企业性质
        if (StringUtils.isNotBlank(attrJob.getEnterpriseNature())){
            // 民营、外企才判断是否是优质企业
            if ("CUS_KHZZ_JOB_QYXZ_4".equals(attrJob.getEnterpriseNature()) || "CUS_KHZZ_JOB_QYXZ_5".equals(attrJob.getEnterpriseNature())){
                if (null != attrJob.getIsQuality() && 1 == attrJob.getIsQuality()){
                    totalBigDecimal = totalBigDecimal.add(new BigDecimal("2.5"));
                } else {
                    totalBigDecimal = totalBigDecimal.add(new BigDecimal("2"));
                }
            } else {
                totalBigDecimal = getTreeBookScore(attrJob.getEnterpriseNature(), totalBigDecimal);
            }
        }
        // 工资
        if (null != attrJob.getWages()){
            Double wages = attrJob.getWages();
            if (wages < 3000){
                totalBigDecimal = totalBigDecimal.add(new BigDecimal("0.5"));
            } else if (wages >= 3000 && wages < 5000 ){
                totalBigDecimal = totalBigDecimal.add(new BigDecimal("1"));
            } else if (wages >= 5000 && wages < 10000 ){
                totalBigDecimal = totalBigDecimal.add(new BigDecimal("1.5"));
            } else if (wages >= 10000){
                totalBigDecimal = totalBigDecimal.add(new BigDecimal("2"));
            }
        }
        //  工资发放方式
        if (StringUtils.isNotBlank(attrJob.getWagesPayForm())){
            totalBigDecimal = getTreeBookScore(attrJob.getWagesPayForm(), totalBigDecimal);
        }
        return totalBigDecimal;
    }

    /**
     * 计算保单分数
     * @param attrPolicy 保单
     * @param totalBigDecimal 总分数
     */
    private BigDecimal addPolicyScore(AttrPolicy attrPolicy, BigDecimal totalBigDecimal) {
        // 缴费年限
        if (StringUtils.isNotBlank(attrPolicy.getPaymentYears())){
            totalBigDecimal = getTreeBookScore(attrPolicy.getPaymentYears(), totalBigDecimal);
        }
        // 缴费次数 默认满分
        totalBigDecimal = totalBigDecimal.add(new BigDecimal("2.25"));
        // 投保人
        if (StringUtils.isNotBlank(attrPolicy.getPolicyHolder())){
            totalBigDecimal = getTreeBookScore(attrPolicy.getPaymentYears(), totalBigDecimal);
        }
        // 是否断缴
        if (null != attrPolicy.getIsPaidOff()){
            // 未断缴
            if (0 == attrPolicy.getIsPaidOff()){
                totalBigDecimal = totalBigDecimal.add(new BigDecimal("1.5"));
            }
        }
        // 是否变更投保人
        if (null != attrPolicy.getIsChange()){
            // 未断缴
            if (0 == attrPolicy.getIsChange()){
                totalBigDecimal = totalBigDecimal.add(new BigDecimal("0.75"));
            }
        }
        return totalBigDecimal;
    }

    /**
     * 根据客户基本信息计算分数
     * @param customer 客户信息
     * @param totalBigDecimal 总分数
     */
    private BigDecimal addBaseInfoScore(Customer customer, BigDecimal totalBigDecimal) {
        // 年龄
        if (null != customer.getAge()){
            Integer age = customer.getAge();
            String ageDecimal = "0";
            if (age >= 18 && age < 20){
                ageDecimal = "2";
            } else if (age >= 20 && age < 25){
                ageDecimal = "3";
            } else if (age >= 25 && age < 55){
                ageDecimal = "4";
            } else if (age >= 55 && age < 65){
                ageDecimal = "3";
            } else if (age >= 65 ){
                ageDecimal = "2";
            }
            totalBigDecimal = totalBigDecimal.add(new BigDecimal(ageDecimal));
        }
        // 户口所在地
        if (StringUtils.isNotBlank(customer.getRegisteredResidence())){
            String registeredResidence = customer.getRegisteredResidence();
            if (registeredResidence.contains("成都") || registeredResidence.contains("成都市")){
                totalBigDecimal = totalBigDecimal.add(new BigDecimal("1"));
            } else{
                totalBigDecimal = totalBigDecimal.add(new BigDecimal("0.5"));
            }

        }
        // 婚姻状况
        if (StringUtils.isNotBlank(customer.getMaritalStatus())){
            totalBigDecimal = getTreeBookScore(customer.getMaritalStatus(), totalBigDecimal);
        }
        // 民族 默认满分
        totalBigDecimal = totalBigDecimal.add(new BigDecimal("2"));

        // 学历
        if (StringUtils.isNotBlank(customer.getEduBackground())){
            totalBigDecimal = getTreeBookScore(customer.getEduBackground(), totalBigDecimal);
        }
        return totalBigDecimal;
    }

    /**
     * 计算车辆分数
     * @param attrVehicle 车辆数据
     * @param totalBigDecimal 总分数
     */
    private BigDecimal addVehicleScore(AttrVehicle attrVehicle, BigDecimal totalBigDecimal) {
        // 购车时间
        if (null != attrVehicle.getBuyingTime()){
            // 5年以内
            if (new Date().compareTo(CalendarUtils.addYears(attrVehicle.getBuyingTime(),5)) == -1){
                totalBigDecimal = totalBigDecimal.add(new BigDecimal("0.5"));
            } else {
                totalBigDecimal = totalBigDecimal.add(new BigDecimal("0.3"));
            }
        }
        // 裸车价
        if (null != attrVehicle.getBareCarPrice()){
            Double bareCarPrice = attrVehicle.getBareCarPrice();
            if (bareCarPrice < 8){
                totalBigDecimal = totalBigDecimal.add(new BigDecimal("0.5"));
            } else if (bareCarPrice >= 8 && bareCarPrice < 20){
                totalBigDecimal = totalBigDecimal.add(new BigDecimal("1"));
            } else if (bareCarPrice >= 20 && bareCarPrice < 50){
                totalBigDecimal = totalBigDecimal.add(new BigDecimal("1.1"));
            } else if (bareCarPrice >= 50 && bareCarPrice < 100){
                totalBigDecimal = totalBigDecimal.add(new BigDecimal("1.3"));
            } else if (bareCarPrice >= 100){
                totalBigDecimal = totalBigDecimal.add(new BigDecimal("1.5"));
            }
        }
        // 万公里数
        if (null != attrVehicle.getKilometer()){
            if (attrVehicle.getKilometer() < 7){
                totalBigDecimal = totalBigDecimal.add(new BigDecimal("0.5"));
            }
        }
        // 车辆类型 默认满分
        if (StringUtils.isNotBlank(attrVehicle.getVehicleType())){
            totalBigDecimal = totalBigDecimal.add(new BigDecimal("0.25"));
        }
        // 是否被抵押
        if (null != attrVehicle.getIsMortgage()){
            if (1 == attrVehicle.getIsMortgage()){
                totalBigDecimal = totalBigDecimal.add(new BigDecimal("0.1"));
            } else {
                totalBigDecimal = totalBigDecimal.add(new BigDecimal("0.25"));
            }
        }
        // 车牌地域
        if (StringUtils.isNotBlank(attrVehicle.getVehicleArea())){
            if (attrVehicle.getVehicleArea().contains("川A")){
                totalBigDecimal = totalBigDecimal.add(new BigDecimal("1"));
            } else if (attrVehicle.getVehicleArea().contains("川")) {
                totalBigDecimal = totalBigDecimal.add(new BigDecimal("0.5"));
            }
        }
        // 购买方式
        if (null != attrVehicle.getPayType()){
            // 全款
            if (1 == attrVehicle.getPayType()){
                totalBigDecimal = totalBigDecimal.add(new BigDecimal("1"));
            } else {
                totalBigDecimal = totalBigDecimal.add(new BigDecimal("0.5"));
            }
        }
        return totalBigDecimal;
    }

    /**
     * 计算房产分数
     * @param attrBuilding 房产数据
     * @param totalBigDecimal 总分数
     */
    private BigDecimal addBuildingScore(AttrBuilding attrBuilding, BigDecimal totalBigDecimal) {
        // 房屋类型
        if (StringUtils.isNotBlank(attrBuilding.getBuildingType())){
            totalBigDecimal = getTreeBookScore(attrBuilding.getBuildingType(), totalBigDecimal);
        }
        // 建房时间
        if (StringUtils.isNotBlank(attrBuilding.getBuiltUpTime())){
            Integer nowYear = CalendarUtils.getYear(new Date());
            // 二十年以内
            if (nowYear.intValue() - Integer.parseInt(attrBuilding.getBuiltUpTime()) < 20){
                totalBigDecimal = totalBigDecimal.add(new BigDecimal("1.25"));
            } else {
                totalBigDecimal = totalBigDecimal.add(new BigDecimal("1"));
            }
        }
        // 房屋位置
        if (StringUtils.isNotBlank(attrBuilding.getBuildingPosition())){
            totalBigDecimal = getTreeBookScore(attrBuilding.getBuildingPosition(), totalBigDecimal);
        }
        // 房屋面积
        if (StringUtils.isNotBlank(attrBuilding.getBuildingArea())){
            totalBigDecimal = getTreeBookScore(attrBuilding.getBuildingArea(), totalBigDecimal);
        }
        // 市场价
        if (null != attrBuilding.getMarketPrice()){
            // 100万以内
            if (attrBuilding.getMarketPrice() < 100L){
                totalBigDecimal = totalBigDecimal.add(new BigDecimal("1"));
            } else {
                totalBigDecimal = totalBigDecimal.add(new BigDecimal("1.25"));
            }
        }
        // 房产证
        if (StringUtils.isNotBlank(attrBuilding.getCertificate())){
            totalBigDecimal = getTreeBookScore(attrBuilding.getCertificate(), totalBigDecimal);
            // 有证
            if (!"CUS_KHZZ_HOUSE_FCZ_1".equals(attrBuilding.getCertificate())){
                totalBigDecimal = totalBigDecimal.add(new BigDecimal("1.25"));
            }
        }
        //购房方式
        if (null != attrBuilding.getPayType()){
            // 全款
            if (attrBuilding.getPayType() == 1){
                totalBigDecimal = totalBigDecimal.add(new BigDecimal("2.5"));
            } else {
                totalBigDecimal = totalBigDecimal.add(new BigDecimal("1.5"));
            }
        }
        //是否可以交易
        if (null != attrBuilding.getIsTrade()){
            // 可以交易
            if (attrBuilding.getIsTrade() == 1){
                totalBigDecimal = totalBigDecimal.add(new BigDecimal("0.625"));
            }
        }
        return totalBigDecimal;
    }

    /**
     * 根据code获取字典中定义的ext1（分数）值
     * @param code 属性code
     * @param totalBigDecimal 总分数
     */
    private BigDecimal getTreeBookScore(String code, BigDecimal totalBigDecimal) {
        TreeBook treeBook = treeBookService.queryTreeBookByCode(code);
        if (null != treeBook){
            String ext1 = treeBook.getExt1();
            if (StringUtils.isNotBlank(ext1) && StringUtils.isNumber(ext1)){
                totalBigDecimal =  totalBigDecimal.add(new BigDecimal(ext1));
            }
        }
        return totalBigDecimal;
    }

    /**
     * 根据指定的客户属性类和客户id返回相应的客户属性集合
     * @param attrClass 客户属性类class
     * @param customerId 客户id
     * @return 属性集合
     */
    @SuppressWarnings("unchecked")
    private <T> List<T> listAttrByClassAndCustomerId(Class<T> attrClass, Long customerId){
        return repository.getSession().createCriteria(attrClass).add(Restrictions.eq("customerId",customerId)).list();
    }

}
